package base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*String methodName = req.getParameter("methodName");
        System.out.println(methodName);*/
        String methodName = null;

        String contentType = req.getHeader("Content-Type");

        if("application/json;charset=utf-8".equals(contentType)){
            String postJSON = getPostJSON(req);

            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);

            methodName = (String)map.get("methodName");

            req.setAttribute("map",map);
        }else {
            methodName = req.getParameter("methodName");
        }
        if (methodName != null){
            try {
                Class c = this.getClass();
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this,req,resp);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("请求的功能不存在！！！！");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**    
     *  POST请求格式为 application/json;charset=utf-8    
     *  在这个方法中我们使用流的方式,获取到POST请求的数据    
     **/
    public String getPostJSON(HttpServletRequest request){
        try {
            //从reque中获取缓冲输入流对象
            BufferedReader reader = request.getReader();

            //创建StringBuffer保存读取出的数据
            StringBuffer sb = new StringBuffer();

            //循环读取
            String line = null;
            while ((line = reader.readLine())!=null){
                sb.append(line);
            }
            //返回结果
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
